﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Windows;
using System.Xml.Serialization;
using ForecastManager.Dialogs;

namespace ForecastManager
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow
	{
		public MainWindow()
		{
			InitializeComponent();

			snapshotWall.SnapshotDir = GetDataFolderPath();

			ExploreExistedSnapshots();
			snapshotWall.SelectionChanged += SnapshotWallSelectionChanged;
			
		}

		/// <summary>
		/// Событие выбора снапшота.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void SnapshotWallSelectionChanged(object sender, EventArgs e)
		{
			//snapshotWall.SelectedSnapshotBrick
			//throw new NotImplementedException();
		}

		private string GetDataFolderPath()
		{
			return ConfigurationManager.AppSettings["dataFolder"];
		}

		private void ExploreExistedSnapshots()
		{
			string dataDirectory = GetDataFolderPath();
			string[] forecastShotsFiles = Directory.GetFiles(dataDirectory, "*.bfs", 
				SearchOption.TopDirectoryOnly);
			
			if (forecastShotsFiles.Length > 0)
			{
				List<Snapshot> snapshots = new List<Snapshot>(forecastShotsFiles.Length);
				foreach (var forecastShotFile in forecastShotsFiles)
				{
					Snapshot snapshot = DeserializeForecastSnapshotFromString(forecastShotFile);
					if (snapshot == null)
					{
						LogMessage(String.Format("Не удалось десериализовать файл сника '{0}'.", 
							forecastShotFile));
					}
					else
					{
						snapshots.Add(snapshot);
					}
				}

				//отображаем снимки на экране
				ShowSnapshotsList(snapshots);
			}
		}

		/// <summary>
		/// Создание "кирпичей" прогнозных снимков и размещение их на форме.
		/// </summary>
		/// <param name="snapshots">Список снимков.</param>
		private void ShowSnapshotsList(List<Snapshot> snapshots)
		{
			snapshotWall.PutBricks(snapshots);
		}

		/// <summary>
		/// Десериализация файла снимка прогноза.
		/// </summary>
		/// <param name="snapshotPath">Путь к файлу.</param>
		/// <returns></returns>
		private Snapshot DeserializeForecastSnapshotFromString(string snapshotPath)
		{
			Snapshot snapshot = null;
			try
			{
				TextReader reader = new StreamReader(snapshotPath);
				XmlSerializer snapshotSerializer = new XmlSerializer(typeof(Snapshot));
				snapshot = (Snapshot)snapshotSerializer.Deserialize(reader);
			}
			catch (Exception ex)
			{
				LogMessage(String.Format("Ошибка при десериализации: {0}.", ex));
			}
			return snapshot;
		}

		/// <summary>
		/// Сохранение снимка.
		/// </summary>
		/// <param name="snapshot"></param>
		private void SerializeForecastSnapshot(Snapshot snapshot)
		{
			string path = GetDataFolderPath() + snapshot.SnapshotName + ".bfs";
			Snapshot.Serialize(path, snapshot);
		}

		/// <summary>
		/// Логирование информации в экранный лог.
		/// </summary>
		/// <param name="message"></param>
		private void LogMessage(string message)
		{
			if (LogTextBlock.Dispatcher.CheckAccess())
			{
				LogTextBlock.Text = message + "\r\n" + LogTextBlock.Text;
			}
			else
			{
				LogTextBlock.Dispatcher.Invoke(new Action(() => LogMessage(message)), new object[] { });
			}
		}

		/// <summary>
		/// Загрузка прогноза.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void LoadForecastButtonClick(object sender, RoutedEventArgs e)
		{
			LoadForecastDialog loadForecastDialog = new LoadForecastDialog();
			bool? dialogResult = loadForecastDialog.ShowDialog();
			if (dialogResult.HasValue && dialogResult.Value)
			{
				Snapshot snapshot = loadForecastDialog.Snapshot;
				SerializeForecastSnapshot(snapshot);
			}
		}
	}
}
